Fork me on GitHub

67. Add Binary

67. Add Binary

题目

 Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100". 

解析

  • 自己写的思路比较麻烦,特别注意字符串string的str[0]是从左边开始的,错过几次了
  • 主要考虑进位的几种情况
  • 有一种是:思路很简单,先把短的字符串补齐,然后逐位相加。
// 67. Add Binary
class Solution_67 {
public:
	string addBinary(string a, string b) {

		string ret;
		int len = (a.size() < b.size()) ? a.size() : b.size();
		bool falg = false; //进位标志
		reverse(a.begin(), a.end());
		reverse(b.begin(), b.end());

		for (int i = 0; i < len;i++)
		{
			if (a[i]=='1'&&b[i]=='1')
			{
				if (falg)
				{
					ret.push_back('1');
				}
				else
				{
					ret.push_back('0');
				}
				falg = true;
			}
			else if ((a[i] == '1'&&b[i] == '0') || (a[i] == '0'&&b[i] == '1'))
			{
				if (falg)
				{
					ret.push_back('0');
					falg = true;
				}
				else
				{
					ret.push_back('1');
					falg = false;
				}
			}
			else if (a[i] == '0'&&b[i] == '0')
			{
				if (falg)
				{
					ret.push_back('1');
				}
				else
				{
					ret.push_back('0');
				}
				falg = false;
			}
		}
		
		int len_max = max(a.size(),b.size());
		int len_min = min(a.size(),b.size());
		for (int i = len_min; i < len_max; i++)
		{
			if (a.size() >= b.size())
			{
				if (a[i] == '1'&&falg)
				{

					ret.push_back('0');
					falg = true;

				}
				else if (a[i] == '0'&&falg)
				{

					ret.push_back('1');
					falg = false;
				}
				else
				{
					ret.push_back(a[i]);
				}
			}
			else
			{
				if (b[i] == '1'&&falg)
				{

					ret.push_back('0');
					falg = true;

				}
				else if (b[i] == '0'&&falg)
				{

					ret.push_back('1');
					falg = false;
				}
				else
				{
					ret.push_back(b[i]);
				}
			}
		}
		if (falg)
		{
			ret.push_back('1');
		}
		reverse(ret.begin(), ret.end());
		return ret;
	}
};


题目来源

posted @ 2018-03-22 16:37  ranjiewen  阅读(146)  评论(0编辑  收藏  举报